package com.foodorder.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 购物车服务 - 处理购物车数据同步
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CartService {

    private final StringRedisTemplate redisTemplate;
    private final ObjectMapper objectMapper;
    
    // Redis key前缀
    private static final String CART_KEY_PREFIX = "cart:user:";
    private static final String CART_COUNT_KEY_PREFIX = "cart:count:user:";
    
    // 过期时间：30天
    private static final long CART_EXPIRE_DAYS = 30;
    
    /**
     * 保存购物车数据
     */
    public void saveCartItems(Long userId, String deviceId, List<Map<String, Object>> cartItems) {
        try {
            // 将购物车数据转换为JSON
            String cartJson = objectMapper.writeValueAsString(cartItems);
            
            // 保存到Redis
            String cartKey = CART_KEY_PREFIX + userId;
            redisTemplate.opsForValue().set(cartKey, cartJson, CART_EXPIRE_DAYS, TimeUnit.DAYS);
            
            // 保存购物车商品数量
            int itemCount = calculateItemCount(cartItems);
            String countKey = CART_COUNT_KEY_PREFIX + userId;
            redisTemplate.opsForValue().set(countKey, String.valueOf(itemCount), CART_EXPIRE_DAYS, TimeUnit.DAYS);
            
            log.info("用户{}的购物车已保存, 设备ID: {}, 商品数量: {}", userId, deviceId, cartItems.size());
        } catch (JsonProcessingException e) {
            log.error("保存购物车失败: {}", e.getMessage(), e);
            throw new RuntimeException("保存购物车失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取购物车数据
     */
    public Map<String, Object> getCartItems(Long userId, String deviceId) {
        String cartKey = CART_KEY_PREFIX + userId;
        String cartJson = redisTemplate.opsForValue().get(cartKey);
        
        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("deviceId", deviceId);
        result.put("timestamp", System.currentTimeMillis());
        
        if (cartJson != null) {
            try {
                List<Map<String, Object>> cartItems = objectMapper.readValue(cartJson, 
                    objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
                
                result.put("cartItems", cartItems);
                log.info("获取用户{}的购物车成功, 设备ID: {}, 商品数量: {}", userId, deviceId, cartItems.size());
            } catch (JsonProcessingException e) {
                log.error("解析购物车数据失败: {}", e.getMessage(), e);
                result.put("cartItems", new ArrayList<>());
            }
        } else {
            // 如果没有购物车数据，返回空列表
            result.put("cartItems", new ArrayList<>());
            log.info("用户{}没有购物车数据", userId);
        }
        
        return result;
    }
    
    /**
     * 清空购物车
     */
    public void clearCart(Long userId) {
        String cartKey = CART_KEY_PREFIX + userId;
        String countKey = CART_COUNT_KEY_PREFIX + userId;
        
        redisTemplate.delete(cartKey);
        redisTemplate.delete(countKey);
        
        log.info("用户{}的购物车已清空", userId);
    }
    
    /**
     * 获取购物车商品数量
     */
    public int getCartItemCount(Long userId) {
        String countKey = CART_COUNT_KEY_PREFIX + userId;
        String countStr = redisTemplate.opsForValue().get(countKey);
        
        if (countStr != null) {
            try {
                return Integer.parseInt(countStr);
            } catch (NumberFormatException e) {
                log.error("购物车数量格式错误: {}", e.getMessage());
            }
        }
        
        // 如果没有缓存的数量或解析失败，则重新计算
        return recalculateCartItemCount(userId);
    }
    
    /**
     * 重新计算购物车商品数量
     */
    private int recalculateCartItemCount(Long userId) {
        String cartKey = CART_KEY_PREFIX + userId;
        String cartJson = redisTemplate.opsForValue().get(cartKey);
        
        if (cartJson != null) {
            try {
                List<Map<String, Object>> cartItems = objectMapper.readValue(cartJson, 
                    objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class));
                
                int count = calculateItemCount(cartItems);
                
                // 更新缓存
                String countKey = CART_COUNT_KEY_PREFIX + userId;
                redisTemplate.opsForValue().set(countKey, String.valueOf(count), CART_EXPIRE_DAYS, TimeUnit.DAYS);
                
                return count;
            } catch (JsonProcessingException e) {
                log.error("解析购物车数据失败: {}", e.getMessage(), e);
            }
        }
        
        return 0;
    }
    
    /**
     * 计算购物车商品总数量
     */
    private int calculateItemCount(List<Map<String, Object>> cartItems) {
        int count = 0;
        
        for (Map<String, Object> item : cartItems) {
            if (item.containsKey("quantity")) {
                Object quantity = item.get("quantity");
                if (quantity instanceof Number) {
                    count += ((Number) quantity).intValue();
                } else if (quantity instanceof String) {
                    try {
                        count += Integer.parseInt((String) quantity);
                    } catch (NumberFormatException e) {
                        log.warn("购物车商品数量格式无效: {}", quantity);
                    }
                }
            }
        }
        
        return count;
    }
} 